using System;
using Azure.Domain.Models;
using Azure.Infrastructure;
using StructureMap;

namespace Azure.Domain.Services
{
    public interface IBlogConfiguration
    {
        SiteConfiguration Configuration { get; }
        void Save(SiteConfiguration configuration);
    }

    public class BlogConfiguration : IBlogConfiguration
    {
        private readonly object _lockObject = new object();
        private SiteConfiguration _configuration;
        private readonly IContainer _container;

        public BlogConfiguration(IContainer container)
        {
            _container = container;
        }
        
        public SiteConfiguration Configuration
        {
            get
            {
                EnsureConfigurationLoaded();
                return _configuration;
            }
        }

        public void Save(SiteConfiguration configuration)
        {
            EnsureConfigurationLoaded();
            var repository = _container.GetInstance<IRepository<SiteConfiguration>>();

            lock (_lockObject)
            {
                if (_configuration is NullSiteConfiguration)
                {
                    repository.Insert(configuration);
                }
                else
                {
                    repository.Attach(configuration);
                    repository.Update(configuration);
                }

                _configuration = configuration;
            }
        }

        protected virtual void EnsureConfigurationLoaded()
        {
            if (_configuration == null)
            {
                lock (_lockObject)
                {
                    if (_configuration == null)
                    {
                        var repository = _container.GetInstance<IRepository<SiteConfiguration>>();
                        _configuration =
                            repository.Load(SiteConfiguration.PartitionKeyValue, SiteConfiguration.RowKeyValue) ??
                            new NullSiteConfiguration();
                    }
                }
            }
        }

        public class NullSiteConfiguration : SiteConfiguration
        {
            public NullSiteConfiguration()
            {
                Title = "Please Configure This";
                SubTitle = "Please configure this";
                Owner = "Unconfigured Site";
                Email = "unconfigured@site.com";
            }
        }
    }
} 